package com.easylive.app.video;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.easylive.app.R;
import com.easylive.app.service.MediaService;

import java.util.ArrayList;
import java.util.Arrays;

public class VideoPlayerActivity extends Activity {
    private static final String TAG = "VPA";
    private final String[] mVideoUrls = {"https://vt1.doubanio.com/202301311354/f4e93bed7d3796c6cced563accb601b5/view/movie/M/402990704.mp4", "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318231014076505.mp4"};
    private VideoPlayerView mVideoView;
    private BroadcastReceiver mLocalBr = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "receive msg:" + intent);
            if (intent != null) {
                String msg = intent.getStringExtra("msg");
                if ("all_exit".equals(msg) || "photo_play".equals(msg)) {
                    finish();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
        initVideoSource();
        registerMsg();
    }

    private void initVideoSource() {
        mVideoView = findViewById(R.id.video_view);
        ArrayList<String> serverData = getIntent().getStringArrayListExtra("data");
        if (serverData != null && !serverData.isEmpty()) {
            mVideoView.setVideoSourceList(serverData);
        } else {
            mVideoView.setVideoSourceList(Arrays.asList(mVideoUrls));
        }
        mVideoView.start();
        mVideoView.setOnClickListener(view -> {
            MediaService.isPlaying = false;
            finish();
        });
    }

    private void registerMsg() {
        IntentFilter intentFilter = new IntentFilter(MediaService.SERVICE_MSG_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mLocalBr, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVideoView.pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mVideoView.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBr);
    }
}